package fr.paris.lutece.plugins.techos.web.chat;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import fr.paris.lutece.plugins.genericjpa.service.IGenericJPAService;
import fr.paris.lutece.plugins.genericjpa.web.GenericJPAJspBean;
import fr.paris.lutece.plugins.techos.bean.chat.Chat;
import fr.paris.lutece.plugins.techos.bean.chat.ChatFilter;
import fr.paris.lutece.plugins.techos.dto.chat.ChatDTO;
import fr.paris.lutece.plugins.techos.service.chat.IChatService;
import fr.paris.lutece.portal.service.admin.AccessDeniedException;
import fr.paris.lutece.portal.service.message.AdminMessage;
import fr.paris.lutece.portal.service.message.AdminMessageService;
import fr.paris.lutece.portal.service.spring.SpringContextService;
import fr.paris.lutece.portal.service.template.AppTemplateService;
import fr.paris.lutece.portal.web.constants.Messages;
import fr.paris.lutece.util.beanvalidation.ValidationError;
import fr.paris.lutece.util.datatable.DataTableManager;
import fr.paris.lutece.util.html.HtmlTemplate;


/**
 * The Chat Jsp Bean
 * 
 * @author jchaline
 */
public class ChatJspBean extends GenericJPAJspBean<Integer, Chat>
{

    public static final Logger LOGGER = Logger.getLogger( ChatJspBean.class );
    public static final long serialVersionUID = 2080010224221425278L;
    public static final String RIGHT_MANAGE_CHAT = "TECHOS_CHAT_MANAGEMENT";

    /* PARAMETERS */
    private static final String PARAMETER_PREFIX_BEAN_FIELD = "techos.chat.field.";

    /* JSP URL */
    public static final String JSP_MANAGE_BEAN = "jsp/admin/plugins/techos/chat/ManageChat.jsp";
    private static final String JSP_DO_DELETE_CHAT = "jsp/admin/plugins/techos/chat/DoDeleteChat.jsp";

    /* I18N KEYS */
    private static final String I18N_CONFIRMATION_DELETE_CHAT = "techos.chat.delete.confirmation";
    private static final String I18N_TITLE_DELETE_CHAT = "techos.chat.delete.title";

    /* BEANS */
    private static final String BEAN_CHAT_SERVICE = "techos.chatService";

    /* TEMPLATES */
    private static final String TEMPLATE_MANAGE_CHAT = "admin/plugins/techos/chat/manage_chat.html";
    private static final String TEMPLATE_CREATE_CHAT = "admin/plugins/techos/chat/save_chat.html";

    private IChatService _serviceChat;

    @Override
    public void init( HttpServletRequest request, String strRight ) throws AccessDeniedException
    {
        super.init( request, strRight );
        _serviceChat = (IChatService) SpringContextService.getBean( BEAN_CHAT_SERVICE );
    }

    @Override
    public String getManageBean( HttpServletRequest request )
    {
        LOGGER.debug( "getManageBean" );
        Map<String, Object> model = super.getManageBeanModel( request );
        ChatFilter filter = new ChatFilter( );
        populate( filter, request );

        DataTableManager<Chat> dataTableUser = getDataTable( request, filter );

        model.put( MARK_DATA_TABLE_BEAN, dataTableUser );
        model.put( MARK_FILTER, filter );

        HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_MANAGE_CHAT, getLocale( ), model );

        dataTableUser.clearItems( );

        return getAdminPage( template.getHtml( ) );
    }

    /**
     * Get the DataTableManager object for the ShowDTO bean
     * @param request the http request
     * @param filter the filter
     * @return the data table to use
     */
    private DataTableManager<Chat> getDataTable( HttpServletRequest request, ChatFilter filter )
    {
        //si un objet est déjà présent en session, on l'utilise

        DataTableManager<Chat> dataTableToUse = getAbstractDataTableManager( request, filter, MARK_DATA_TABLE_BEAN,
                JSP_MANAGE_BEAN, Chat.class );

        //si pas d'objet en session, il faut ajouter les colonnes à afficher
        if ( dataTableToUse.getListColumn( ).isEmpty( ) )
        {
            dataTableToUse.addColumn( "techos.chat.field.name", "name", false );
            dataTableToUse.addColumn( "techos.chat.field.date", "date?date", false );
            dataTableToUse.addFreeColumn( "techos.transverse.actions", PARAMETER_MACRO_COLUMN_ACTIONS_BEAN );
        }
        saveDataTableInSession( request, dataTableToUse, MARK_DATA_TABLE_BEAN );
        return dataTableToUse;
    }

    @Override
    public String getSaveBean( HttpServletRequest request )
    {
        Map<String, Object> model = super.getSaveBeanModel( request );

        if ( model.containsKey( MARK_BEAN ) )
        {
            Object bean = model.get( MARK_BEAN );
            if ( bean instanceof Chat )
            {
                ChatDTO chatDTO = ChatDTO.convertEntity( (Chat) bean );
                model.put( MARK_BEAN, chatDTO );
            }
        }

        HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_CREATE_CHAT, getLocale( ), model );

        return getAdminPage( template.getHtml( ) );
    }

    @Override
    public String doSaveBean( HttpServletRequest request )
    {
        if ( null != request.getParameter( PARAMETER_CANCEL ) )
        {
            return doGoBack( request, JSP_MANAGE_BEAN );
        }

        ChatDTO dto = new ChatDTO( );
        populate( dto, request );

        /* JSR 303 */
        List<ValidationError> errors = validate( dto, PARAMETER_PREFIX_BEAN_FIELD );

        String urlResult = null;
        //si le dto est valide, il est enregistré en base
        if ( errors.isEmpty( ) )
        {
            _serviceChat.doSaveBean( dto );
            urlResult = doGoBack( request, JSP_MANAGE_BEAN );
        }
        //sinon, il faut gerer ces erreurs, manuellement ou via le service lutece
        else
        {
            urlResult = AdminMessageService.getMessageUrl( request, Messages.MESSAGE_INVALID_ENTRY, errors );
        }

        return urlResult;
    }

    @Override
    public String getDeleteBean( HttpServletRequest request )
    {
        String strBeanId = request.getParameter( MARK_BEAN_ID );

        Map<String, Object> urlParam = new HashMap<String, Object>( );
        urlParam.put( MARK_BEAN_ID, strBeanId );

        return AdminMessageService.getMessageUrl( request, I18N_CONFIRMATION_DELETE_CHAT, null, I18N_TITLE_DELETE_CHAT,
                JSP_DO_DELETE_CHAT, "_self", AdminMessage.TYPE_CONFIRMATION, urlParam, JSP_MANAGE_BEAN );
    }

    @Override
    public String doDeleteBean( HttpServletRequest request )
    {
        String strChatId = request.getParameter( MARK_BEAN_ID );
        Integer nIdBean = Integer.valueOf( strChatId );

        _serviceChat.doDeleteBean( nIdBean );

        return doGoBack( request, JSP_MANAGE_BEAN );
    }

    @Override
    protected IGenericJPAService<Integer, Chat> getBeanService( )
    {
        IGenericJPAService<Integer, Chat> service = null;
        if ( _serviceChat instanceof IGenericJPAService )
        {
            service = _serviceChat;
        }
        return service;
    }

}